package com.company.genealogy.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebConfig 配置类的作用：
 * 
 * 1. 通过实现 WebMvcConfigurer 接口，允许自定义 Spring MVC 的相关配置。
 * 2. 通过 @Value 注解读取 application.yml 中的 upload.path 配置（如 /Volumes/czx1/logs/upload）。
 * 3. 在 addResourceHandlers 方法中，将 /uploads/** 路径映射到本地文件系统的 uploadPath 目录，实现静态资源（如图片、文件）对外访问。
 *    例如：访问 http://localhost:8080/uploads/xxx.jpg 实际读取的是本地 /Volumes/czx1/logs/upload/xxx.jpg 文件。
 *    访问 http://localhost:8080/member-photos/yyyy/MM/dd/xxx.png 实际读取的是 /Volumes/czx1/logs/upload/member-photos/yyyy/MM/dd/xxx.png
 * 
 * 这样可以方便地将用户上传的文件通过 HTTP 方式访问，无需额外开发下载接口，后期可直接用nginx做静态资源代理。
 * 
 * @author chenzhixiang
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${upload.path:/Volumes/czx1/logs/upload}")
    private String uploadPath;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 将 /uploads/** 映射到本地文件系统的 uploadPath 目录
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadPath + "/");
        
        // 将 /member-photos/** 映射到本地文件系统的 uploadPath/member-photos 目录
        registry.addResourceHandler("/member-photos/**")
                .addResourceLocations("file:" + uploadPath + "/member-photos/");
        
        // 将 /spouse-photos/** 映射到本地文件系统的 uploadPath/spouse-photos 目录
        registry.addResourceHandler("/spouse-photos/**")
                .addResourceLocations("file:" + uploadPath + "/spouse-photos/");
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
} 